const _ = require('lodash');
const moment = require('moment');

function tansParams(params) {
  return _.chain(params)
    .omitBy(_.isNil) // 移除null、undefined的值
    .map((value, key) => {
      if (_.isPlainObject(value)) {
        return _.map(value, (subValue, subKey) =>
          `${encodeURIComponent(`${key}[${subKey}]`)}=${encodeURIComponent(subValue)}`
        ).join('&');
      }
      return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
    })
    .compact() // 移除空值
    .join('&')
    .value();
}
//时间转毫秒级
function timeToMilliseconds(timeStr) {
  // 使用moment更精确
  const time = moment(timeStr, ['HH:mm', 'HH:mm:ss'], true);

  if (!time.isValid()) {
    throw new Error('时间格式不正确');
  }

  return (
    time.hours() * 3600000 +
    time.minutes() * 60000 +
    time.seconds() * 1000
  );
}
// 毫秒级时间戳转时间
function millisecondsToTime(milliseconds) {
  return moment.utc(milliseconds).format('HH:mm:ss');
};

//合并cloudbase的日期时间 时间戳,并返回新的毫秒级时间戳
function combineTimestampsLodash(dateString) {
  // 使用moment更严谨
  return moment(dateString, [
    'YYYY-MM-DD HH:mm:ss',
    'YYYY/MM/DD HH:mm:ss',
    'YYYY-MM-DDTHH:mm:ssZ'
  ]).valueOf();
}
// 时间戳转日期
function formatTimestamp(timestamp, format = 'YYYY-MM-DD') {
  return moment(timestamp).format(format);
}
//日期格式字符串转时间戳
function dateToTimestamp(dateStr) {
  // 使用moment更简洁和强大
  const parsedDate = moment(dateStr, [
    'YYYY-MM-DD',
    'YYYY/MM/DD'
  ], true);

  if (!parsedDate.isValid()) {
    throw new Error('日期格式不正确');
  }

  return parsedDate.valueOf();
}

//课程列表json序列化
function transformRecords(records) {
  const processItem = (item) => {
    if (_.has(item, 'classTime')) {
      item.classTime = _.map(item.classTime, milliseconds =>
        moment.utc(milliseconds).format('HH:mm:ss')
      );
    }

    if (_.has(item, 'classDate')) {
      item.classDate = moment(item.classDate).format('YYYY-MM-DD');
    }

    return item;
  };
  return _.isArray(records) ?
    _.map(records, processItem) :
    processItem(records);
}

//计算是否可以新增课程
function hasOverlap(newTimeRange, existingTimeRanges) {
  return _.some(existingTimeRanges, existingTimeRange =>
    newTimeRange.classTime[0] <= existingTimeRange.classTime[1] &&
    newTimeRange.classTime[1] >= existingTimeRange.classTime[0]
  );
}

//计算用户信息的展示,教师端
function getStatusCounts(arr) {
  if (_.isUndefined(arr) || _.isEmpty(arr)) {
    return {
      total: 0,
      completedCount: 0,
      inProgressCount: 0
    };
  }

  const total = _.size(arr);
  const completedCount = _.size(_.filter(arr, item => item.status === 1 || item.status === 2));
  const inProgressCount = _.size(_.filter(arr, item => item.status === 3 || item.status === 4));

  return {
    total,
    completedCount,
    inProgressCount
  };
}


module.exports = {
  tansParams,
  dateToTimestamp,
  timeToMilliseconds,
  millisecondsToTime,
  formatTimestamp,
  combineTimestampsLodash,
  transformRecords,
  hasOverlap
};